import redis.asyncio as redis
import json
import os
from typing import Optional, Any

# Redis连接配置
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379")

# 创建Redis客户端
redis_client = redis.from_url(REDIS_URL, decode_responses=True)

class CacheService:
    """缓存服务类"""
    
    @staticmethod
    async def set(key: str, value: Any, expire: int = 3600) -> bool:
        """设置缓存"""
        try:
            if isinstance(value, (dict, list)):
                value = json.dumps(value, ensure_ascii=False)
            await redis_client.set(key, value, ex=expire)
            return True
        except Exception as e:
            print(f"缓存设置失败: {e}")
            return False
    
    @staticmethod
    async def get(key: str) -> Optional[Any]:
        """获取缓存"""
        try:
            value = await redis_client.get(key)
            if value:
                try:
                    return json.loads(value)
                except json.JSONDecodeError:
                    return value
            return None
        except Exception as e:
            print(f"缓存获取失败: {e}")
            return None
    
    @staticmethod
    async def delete(key: str) -> bool:
        """删除缓存"""
        try:
            await redis_client.delete(key)
            return True
        except Exception as e:
            print(f"缓存删除失败: {e}")
            return False
    
    @staticmethod
    async def exists(key: str) -> bool:
        """检查缓存是否存在"""
        try:
            return await redis_client.exists(key) > 0
        except Exception as e:
            print(f"缓存检查失败: {e}")
            return False
    
    @staticmethod
    async def set_hash(key: str, mapping: dict, expire: int = 3600) -> bool:
        """设置哈希缓存"""
        try:
            await redis_client.hset(key, mapping=mapping)
            await redis_client.expire(key, expire)
            return True
        except Exception as e:
            print(f"哈希缓存设置失败: {e}")
            return False
    
    @staticmethod
    async def get_hash(key: str) -> Optional[dict]:
        """获取哈希缓存"""
        try:
            return await redis_client.hgetall(key)
        except Exception as e:
            print(f"哈希缓存获取失败: {e}")
            return None

# 缓存键常量
class CacheKeys:
    """缓存键常量类"""
    
    # 数据源缓存
    DATA_SOURCE_PREFIX = "data_source:"
    DASHBOARD_DATA_PREFIX = "dashboard:"
    
    # AI对话缓存
    CHAT_SESSION_PREFIX = "chat_session:"
    AI_RESPONSE_PREFIX = "ai_response:"
    
    # 决策规则缓存
    DECISION_RULE_PREFIX = "decision_rule:"
    
    @staticmethod
    def data_source_key(source_id: int) -> str:
        return f"{CacheKeys.DATA_SOURCE_PREFIX}{source_id}"
    
    @staticmethod
    def dashboard_data_key(data_type: str) -> str:
        return f"{CacheKeys.DASHBOARD_DATA_PREFIX}{data_type}"
    
    @staticmethod
    def chat_session_key(session_id: str) -> str:
        return f"{CacheKeys.CHAT_SESSION_PREFIX}{session_id}"
    
    @staticmethod
    def decision_rule_key(rule_id: int) -> str:
        return f"{CacheKeys.DECISION_RULE_PREFIX}{rule_id}"
